package web.file;

import bean.Manager;
import entity.FileEntity;
import entity.ManagerEntity;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name = "FileUpload",urlPatterns = {"/dao/update/fileUpload"})
@MultipartConfig
public class FileUpload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        String path = request.getServletContext().getRealPath("")+"files";
        Part part = request.getPart("file");//获得
        part.write(path+ File.separator+part.getSubmittedFileName());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName(part.getSubmittedFileName());
        fileEntity.setSize("" + part.getSize());
        fileEntity.setTime(sf.format(new Date()));
        Manager manager = (Manager) request.getSession().getAttribute("manager");
        ManagerEntity managerEntity = em.find(ManagerEntity.class,manager.getMid());
        fileEntity.setMid(managerEntity);
        em.persist(fileEntity);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

}
